package TestCase;

import com.beanit.iec61850bean.ClientAssociation;
import com.beanit.iec61850bean.ClientSap;
import com.beanit.iec61850bean.FileInformation;
import com.beanit.iec61850bean.ServiceError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.CheckUtil;
import util.ErrorCodeMap;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

public class FileServicesTestCase {
    private static final Logger logger = LoggerFactory.getLogger("IEC61850-Client");

    private CheckUtil checkUtil = new CheckUtil();

    private ErrorCodeMap errorCodeMap = new ErrorCodeMap();

    private AssociatedServicesTestCase associatedServicesTestCase = new AssociatedServicesTestCase();

    private static List<FileInformation> GetFileAttributes(ClientAssociation clientAssociationCase ,String filePath) throws ServiceError, IOException {
        List<FileInformation> fileInformationListResult = new ArrayList<>();
        if(filePath.contains("/")){
            List<FileInformation> fileInformationList = clientAssociationCase.getFileDirectory(filePath);
                for (FileInformation item:fileInformationList
                     ) {
                    if (item.getFilename().contains("/")){
                        fileInformationListResult.addAll(GetFileAttributes(clientAssociationCase, filePath+item.getFilename()));
                    } else {
                        List<FileInformation> fileInformationList1 = clientAssociationCase.getFileDirectory(filePath+item.getFilename());
                        for (FileInformation index: fileInformationList1
                             ) {
                            fileInformationListResult.add(
                                    new FileInformation(filePath+index.getFilename(), index.getFileSize(), index.getLastModified())
                            );
                        }

                    }

                }
        } else {
                List<FileInformation> fileInformationList1 = clientAssociationCase.getFileDirectory(filePath);
                for (FileInformation item : fileInformationList1
                     ) {
                    FileInformation index = new FileInformation(filePath+item.getFilename(), item.getFileSize(), item.getLastModified());
                    fileInformationListResult.add(index);
                }
            }
        return fileInformationListResult;
    }


    public boolean GetExistsFileAttributes(String host){
        InetAddress address  = checkUtil.hostCheck(host);
        if(address==null){
            logger.error("Get Exists File Attributes test -------------FAIL");
            return false;
        }
        logger.info("Get Exists File Attributes started!");
        ClientAssociation clientAssociation = associatedServicesTestCase.OpenAssociation(address);
        if (clientAssociation == null){
            logger.error("Get Exists File Attributes test -------------FAIL");
            return false;
        }
        List<FileInformation> fileInformationDirectory;
        try {
            fileInformationDirectory = clientAssociation.getFileDirectory("/");
        } catch (ServiceError serviceError) {
            //serviceError.printStackTrace();
            logger.error("Get Exists[/] File Attributes Error. Error Code: " + errorCodeMap.getErrorName(serviceError.getErrorCode()) + "("+serviceError.getErrorCode()+")");
            logger.error("Get Exists File Attributes test -------------FAIL");
            clientAssociation.disconnect();
            clientAssociation.close();
            return false;
        } catch (IOException e) {
            //e.printStackTrace();
            logger.error("Get Exists[/] File Attributes Error: " + e.getMessage());
            logger.error("Get Exists File Attributes test -------------FAIL");
            clientAssociation.disconnect();
            clientAssociation.close();
            return false;
        }

        List<FileInformation> fileInformationList = new ArrayList<>(fileInformationDirectory);


        for (FileInformation item: fileInformationDirectory
             ) {
            try {
                fileInformationList.addAll(GetFileAttributes(clientAssociation ,item.getFilename()));
            } catch (ServiceError serviceError) {
                //serviceError.printStackTrace();
                logger.error("Get "+ item.getFilename()+" File Attributes Error. Error Code: " + errorCodeMap.getErrorName(serviceError.getErrorCode()) + "("+serviceError.getErrorCode()+")");
                logger.error("Get Exists File Attributes test -------------FAIL");
                clientAssociation.disconnect();
                clientAssociation.close();
                return false;
            } catch (IOException e) {
                //e.printStackTrace();
                logger.error("Get "+ item.getFilename()+" File Attributes Error: " + e.getMessage());
                logger.error("Get Exists File Attributes test -------------FAIL");
                clientAssociation.disconnect();
                clientAssociation.close();
                return false;
            }
        }

        for (FileInformation index:fileInformationList
             ) {
            logger.info("FilePath:[" + index.getFilename() + "] FileSize:["+ index.getFileSize() + "] FileTime:["+ index.getLastModified().getTime().toString()+"]");
        }
        clientAssociation.disconnect();
        clientAssociation.close();
        logger.error("Get Exists File Attributes test -------------PASS");
        return true;
    }

    public boolean GetNoneExistsFileAttributes(String host){
        InetAddress address  = checkUtil.hostCheck(host);
        if(address==null){
            logger.error("Get None Exists File Attributes test -------------FAIL");
            return false;
        }
        logger.info("Get None Exists File Attributes started!");
        ClientAssociation clientAssociation = associatedServicesTestCase.OpenAssociation(address);
        if (clientAssociation == null){
            logger.error("Get None Exists File Attributes test -------------FAIL");
            return false;
        }
        List<Integer> resultCodeId = new ArrayList<>();

        List<String> filePathName = new ArrayList<>();

        filePathName.add("myLeeSen.bin");
        filePathName.add("myFilePath/");
        filePathName.add("myDirectory/myDirectory.log");
        filePathName.add("myTestFile1/myTestFile2/myTestFile3.xml");
        logger.info("Default Test File: " + filePathName);
        for (String filePathNameItem:filePathName
             ) {
            try {
                List<FileInformation> fileInformation = clientAssociation.getFileDirectory(filePathNameItem);
            } catch (ServiceError serviceError) {
                //serviceError.printStackTrace();
                resultCodeId.add(serviceError.getErrorCode());
                logger.info("Get File [" + filePathNameItem + "] Attributes Reply: " + errorCodeMap.getErrorName(serviceError.getErrorCode()) + "("+serviceError.getErrorCode()+")");
                //System.out.println(errorCodeMap.getErrorName(serviceError.getErrorCode()));
            } catch (IOException e) {
                //e.printStackTrace();
                logger.error("Get None Exists File Attributes Error: " + e.getMessage());
                logger.error("Get None Exists File Attributes Test -------------FAIL");
                clientAssociation.disconnect();
                clientAssociation.close();
                return false;
            }
        }
        for (Integer codeId: resultCodeId
             ) {
            if (codeId!=17){
                logger.error("Get None Exists File Attributes Test -------------FAIL");
                clientAssociation.disconnect();
                clientAssociation.close();
                return false;
            }
        }

        clientAssociation.disconnect();
        clientAssociation.close();
        logger.error("Get None Exists File Attributes Test -------------PASS");
        return true;
    }

}
